import os
import graphviz
import subprocess
import pydot


# 读取txt文件中的数据，并转为一个大列表
def read_txt(txt_path):
    file_txt_list = os.listdir(txt_path)
    txt_list = []
    for each in file_txt_list :
        file_txt = open(txt_path+"/"+each,"r")
        each_list = []
        for each_line in file_txt :
            each_line_list = []
            each_line_list = each_line.split(maxsplit=-1)
            each_list.append(each_line_list[0:3])
        txt_list.append(each_list)
        file_txt.close()
    return txt_list

# 把txt里的数据转化为dot文件
def txt_convert_dot(txt_path,dot_path):
    file_txt_list = os.listdir(txt_path)
    txt_list = read_txt(txt_path)
    file_txt_num =0
    for each in txt_list:
        dot_data ="digraph G {\n    graph[rankdir=BT, ratio=3, size=\"10, 20!\"] ;"
        for each_line in each :
            try:
                dot_data = dot_data + "\n    v%s->v%s [label=\"e%s\"];"%(each_line[1],each_line[2],each_line[0])
            except :
                pass
        dot_data = dot_data + "\n}"
        dot_file = open(dot_path+"/"+file_txt_list[file_txt_num]+".dot","w")
        file_txt_num += 1
        dot_file.write(dot_data)
        dot_file.close()
        print("运行完成%s次"%file_txt_num)

# 把dot文件转换为png图片
def dot_convert_png(dot_path,pictures_path):
    dot_exe = "D:/Graphviz/bin/dot.exe"
    dot_file_list = os.listdir(dot_path)
    each_num = 0
    for each in dot_file_list :
        each_file =  dot_path + "/" + each
        each_png_file = pictures_path  + "/" +each
        subprocess.Popen(["%s"%dot_exe,"-Tpng","%s"%each_file,"-o" ,"%s.png"%each_png_file])
        # (graph,) = pydot.graph_from_dot_file(dot_path+"/"+each)
        # graph.write_png(pictures_path+"/"+each+'.png')
        each_num += 1
        print("运行成功%s次"%each_num)







def main():
    txt_path = "D:/hello Python/邓老师任务/test3/data"
    dot_path = "D:/hello Python/邓老师任务/test3/out/dot"
    pictures_path = "D:/hello Python/邓老师任务/test3/out/pictures"
    txt_convert_dot(txt_path,dot_path)
    dot_convert_png(dot_path,pictures_path)

if __name__ == '__main__':
    main()
    